package com.cskaoyan.util;

import lombok.SneakyThrows;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.InvocationHandler;

import java.lang.reflect.Method;

public class ProxyUtil {

    @SneakyThrows
    public static <T> T getServiceProxy(Class<T> clazz){
        T t = clazz.newInstance();
        T proxy = (T) Enhancer.create(clazz, new InvocationHandler() {
            @Override
            public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
                //利用反射赋值
                System.out.println("hello");
                //获得SqlSession并且给Service的mapper成员变量赋值
                Object invoke = method.invoke(t, objects);
                System.out.println("world");
                //提交事务，关闭SqlSession

                return invoke;
            }
        });
        return proxy;
    }
}
